package com.sx.micowell.module.homePage.home

import android.annotation.SuppressLint
import android.text.TextUtils
import com.alibaba.android.arouter.facade.annotation.Route
import com.example.mvvm.base.BaseActivity
import com.example.mvvm.base.data.DataBindingConfig
import com.github.mikephil.charting.data.BarEntry
import com.haibin.calendarview.Calendar
import com.haibin.calendarview.CalendarView
import com.miloyu.modelnet.response.CaloriesRowsVO
import com.miloyu.modelnet.response.DurationRowsVO
import com.miloyu.modelnet.response.WeekRecordVO
import com.sx.micowell.BR
import com.sx.micowell.R
import com.sx.micowell.databinding.FragHomeLastWeekBinding
import com.sx.micowell.framework.app.MyFragment
import com.sx.micowell.framework.arouth.RoutePath
import com.sx.micowell.framework.model.Home2Model
import com.sx.micowell.framework.view.chartManager.initDataChart
import com.sx.micowell.framework.view.chartManager.initHorizontalUIChart
import com.sx.micowell.framework.view.chartManager.initUIChart

/**
 * @Author: YY
 * @Time: 2021/9/7
 * @Describe 首页 - 上周
 */
@Route(path = RoutePath.HOME_LAST_WEEK)
class HomeLastWeekFragment: MyFragment<FragHomeLastWeekBinding, BaseActivity<*>>(), CalendarView.OnWeekChangeListener {

    private lateinit var viewModel: Home2Model

    override fun initViewModel() {
        super.initViewModel()
        viewModel = getFragmentScopeViewModel(Home2Model::class.java)
    }

    override fun getDataBindingConfig(): DataBindingConfig {
        return DataBindingConfig(R.layout.frag_home_last_week, BR.viewModel, viewModel)
    }

    override fun initView() {
        binding.calendarView.setOnWeekChangeListener(this)
        binding.calendarView.scrollToPre()
        binding.calendarView.setMonthViewScrollable(false)
        binding.calendarView.setWeekViewScrollable(false)

        binding.caloriesLine.initHorizontalUIChart()
        binding.monthChart.initUIChart()
    }

    override fun initData() {
        viewModel.reqHome(3)

    }

    @SuppressLint("SetTextI18n")
    override fun initViewObservable() {
        super.initViewObservable()

        // 刷新
        viewModel.ui.refreshEvent.observe(this, {
            binding.refreshLayout.finishRefresh(it)
        })

        viewModel.homeDataEvent.observe(this, {
            // 总时长
            binding.layoutMonth.tvMotionTime.text = "${it.duration}分钟"
            // 总消耗
            binding.layoutMonth.tvCalorie.text = "${it.calorie}"
            // 累计(天)
            binding.layoutMonth.tvRegisterCount.text = "${it.registerCount}"
            // 连续(天)
            binding.layoutMonth.tvRegister.text = "${it.register}"

            val flagRes = if (it.durationIncrease >= 0) R.drawable.ic_svg_sort else R.drawable.ic_svg_drop
            binding.durationFlag.setImageResource(flagRes)

            // 运动时长百分比
            binding.durationIncrease.text = "${it.durationIncrease}"
            // 运动时长最大值
            binding.durationMax.text = "${it.durationMax}"

            calorieChartData(it.caloriesRows)

            monthChart(it.durationRows)

            weekPlanState(it.weekRecord)
        })
    }

    /**
     * 上周计划状态
     */
    private fun weekPlanState(weekRecord: List<WeekRecordVO>) {
        val map : HashMap<String, Calendar> = HashMap()
        if (weekRecord.size > 0 ) {
            map.clear()
            weekRecord.forEach {
                val valueStr = it.targetTime.split("-")
                map[getSchemeCalendar(valueStr[0].toInt(), valueStr[1].toInt(),
                    valueStr[2].toInt(), it.planStatus).toString()] =
                    getSchemeCalendar(valueStr[0].toInt(), valueStr[1].toInt(),
                        valueStr[2].toInt(), it.planStatus)
            }
            //此方法在巨大的数据量上不影响遍历性能，推荐使用
            binding.calendarView.setSchemeDate(map)
        }
    }

    /**
     * 卡路里分布图
     */
    private fun calorieChartData(caloriesRowsList: List<CaloriesRowsVO>) {
        binding.caloriesLine.initDataChart(
            caloriesRowsList.map { BarEntry(caloriesRowsList.indexOf(it).toFloat(), it.calorie.toFloat()) }.toList()
            , caloriesRowsList.filter { !TextUtils.isEmpty(it.title) }.map { it.title }.toList().toTypedArray()
        )
    }

    /**
     * 运动时间分布图
     */
    private fun monthChart(durationRowsList: List<DurationRowsVO>) {
        binding.monthChart.initDataChart(
            durationRowsList.map { BarEntry(durationRowsList.indexOf(it).toFloat(), it.duration.toFloat()) }.toList()
            , durationRowsList.filter { !TextUtils.isEmpty(it.title) }.map { it.title }.toList().toTypedArray()
        )
    }

    private fun getSchemeCalendar(year:Int, month:Int, day: Int, text:String): Calendar {
        val calendar = Calendar()
        calendar.year = year
        calendar.month = month
        calendar.day = day
        calendar.scheme = text
        calendar.addScheme(Calendar.Scheme())
        return calendar
    }

    @SuppressLint("SetTextI18n")
    override fun onWeekChange(weekCalendars: MutableList<Calendar>?) {
        val weekRange = "${weekCalendars?.get(0)?.month}/${weekCalendars?.get(0)?.day}" +
                "—${weekCalendars?.get(6)?.month}/${weekCalendars?.get(6)?.day}"
        // 运动时间
        binding.layoutMonth.tvMotionName.text = "运动总时长 ($weekRange)"
    }

}